using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CrystalController : MonoBehaviour
{
    private Animator anim => GetComponent<Animator>();
    private CircleCollider2D cd => GetComponent<CircleCollider2D>();
    private float existDuration;
    private bool canExplode = true;
    private bool canMove = true;
    private float moveSpeed = 7;
    private Transform closestEnemy;

    private bool canGrow;
    private float growSpeed = 5;

    // Update is called once per frame
    void Update()
    {
        existDuration -= Time.deltaTime;
        if (existDuration < 0)
        {
            FinishCrystal();
        }
        if (canMove && closestEnemy && !canGrow)
        {
            transform.position = Vector2.MoveTowards(transform.position, closestEnemy.position + Vector3.up, moveSpeed * Time.deltaTime);
            if (Vector2.Distance(transform.position, closestEnemy.position) < 1.2f)
                FinishCrystal();
        }

        if (canGrow)
        {
            transform.localScale = Vector2.Lerp(transform.localScale, new Vector2(3, 3), growSpeed * Time.deltaTime);
        }
    }

    public void ChooseRandomEnemy()
    {

    }
    public void SetupCrystal(float _existDuration, bool _canExplode, bool _canMoveToEnemy, float _moveSpeed, Transform target)
    {
        this.existDuration = _existDuration;
        this.canExplode = _canExplode;
        this.canMove = _canMoveToEnemy;
        this.moveSpeed = _moveSpeed;
        this.closestEnemy = target;
    }

    public void FinishCrystal()
    {
        if (canExplode)
        {
            canGrow = true;
            anim.SetTrigger("Explode");
        }
        else
            Destroy(gameObject);
    }

    void AnimationExplodeEvent()
    {
        canExplode = false;
        Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, cd.radius*2.2f);
        foreach (var collider in colliders)
        {
            EnemyData enemy = collider.GetComponent<EnemyData>();
            if (enemy != null)
            {
                PlayerManager.Instance.Player.data.DoDamage(enemy);
            }
        }
    }


}
